TChat.HOST = location.host;
TChat.PORT = 2482;
TChat.TEMPLATE_ID = "tchat";
TChat.date = function(date){
	if(date)
		return date;
	return new Date();
}

function TChat(my_user, to_user) {
	if(to_user){
		this.chat_id = to_user['id'];
	}
	this.HOST = TChat.HOST;
	this.PORT = TChat.PORT;
	this.TEMPLATE_ID = TChat.TEMPLATE_ID;
	
	this.my_user = my_user;
	this.to_user = to_user;
	this.listenXHR;
	
	this.init = function(){
		var This = this;
		$("#" + this.TEMPLATE_ID + "-template").tmpl({'id':this.chat_id}).appendTo("#" + this.TEMPLATE_ID + "-template-container");
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-send-button").click(function(){
			chat.send($("#" + this.TEMPLATE_ID + "-" + This.chat_id + "-textarea").val());
			$("#" + this.TEMPLATE_ID + "-" + This.chat_id + "-textarea").val("");
		});
	}

	this.register = function(){
		var params = "&id=" + this.my_user.id + "&auth_key=" + this.my_user.auth_key + "&username=" + this.my_user.username + "&chat_auth_key=" + this.my_user.chat_auth_key;
		var url = "http://" + this.HOST + ":" + this.PORT + "/chat/users/register?" + params + "&callback=?";
		
		$.ajax({
			url:url,
			dataType: 'json',
			success:  function(data){
				console.log("Registered");
			},
		});

	}
	
	this.open = function(){
		var This = this;
		
		$("#" + this.TEMPLATE_ID + "-template").tmpl({'id':this.chat_id, "username": this.to_user['username']}).appendTo("body");
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-textarea").focus();
		
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-send-button").click(function(){
			console.log("Click");
			chat.send($("#" + this.TEMPLATE_ID + "-" + This.chat_id + "-textarea").val());
			$("#" + this.TEMPLATE_ID + "-" + This.chat_id + "-textarea").val("");
		});
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-textarea").bind("keypress", function(e){
			console.log("textarea key pressed");
			var code = (e.keyCode ? e.keyCode : e.which);
			if(code == 13){
				console.log("Enter pressed");
				This.send($(this).val());
				
				$(this).val("");
				
				return false;
				
			}
		});
		
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-close").click(function(){
			This.close();
		});		
		this.listen();
	}
	

	this.close = function(){
		//$("#" + this.TEMPLATE_ID + "-template-container").empty();
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id).remove();
		
		this.listenXHR.abort()
		var url = "http://" + this.HOST + ":" + this.PORT + "/chat/close?my_id=" + this.my_user['id'] + "&to_id=" + to_user['id'] + "&callback=?";
		var This = this;
		$.getJSON(url, {
		}, function(data){
			console.log("Connection closed");
			console.log(data);
			
		});
	}
	
	this.displayMessage = function(request){
		
		$("#" + this.TEMPLATE_ID + "-message-template").tmpl(
			{
				"message":request['message'], 
				"username": request['username'],
				"date": request['date'],
			}
		).appendTo("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-messages");
		
		
		var scrollHeight = document.getElementById("tchat-" + this.chat_id + "-messages").scrollHeight;
		$("#" + this.TEMPLATE_ID + "-" + this.chat_id + "-messages").animate({scrollTop: scrollHeight}, 'fast');
		
	}
	
	this.listenAll = function(){
		console.log("Listening to chat from all users");
		
		var url = "http://" + this.HOST + ":" + this.PORT + "/chat/listen/all?my_id=" + this.my_user['id'] + "&callback=?";
		var This = this;		
		$.getJSON(url, {
		}, function(data){
			//console.log(data['message']);
			
			console.log("Received a chat from someone");
			console.log(data);
			var user = {};
			user['id'] = data['id'];
			user['username'] = data['username'];
			
			This.to_user = user;
			This.chat_id = This.to_user['id'];
			
			This.open();
				
			This.displayMessage({"message":data['message'], "username": This.to_user['username']});
			
		});
	}
	
	
	this.listen = function(){
		console.log("Listening to chat from user: " + this.to_user['id']);
		
		var url = "http://" + this.HOST + ":" + this.PORT + "/chat/listen?my_id=" + this.my_user['id'] + "&to_id=" + this.to_user['id'] + "&callback=?";
		var This = this;

		this.listenXHR = $.ajax({
			url:url,
			dataType: 'json',
			success:  function(data){
				This.displayMessage(
					{
						"message":data['message'], 
						"username": This.to_user['username'],
						"date": data['date'],
					}
				);
				This.listen();;
			},
			timeout: 100000,
			
			error: function(xhr, status, error) {
        		// Display a generic error for now.
        		//alert("Timeout");
        		console.log("Timeout");
        		This.listen();
      		}
		});
		console.log(this.listenXHR);
	};
	

	this.send = function(message){
	
		var This = this;
		console.log("send chat: " + message);
		var url = "http://" + this.HOST + ":" + this.PORT + "/chat/send?my_id=" + this.my_user['id'] + '&to_id=' + this.to_user['id'] + '&message=' + escape(message) + '&callback=?';
		
		url = url + this.auth_params();
		
		console.log("URL: " + url);
		$.ajax({
			url:url,
			dataType: 'json',
			success:  function(data){
				console.log("Chat sent");
				console.log(data);
				status = "";
				status = data['status'];
				
				This.displayMessage({'message':message, "username": "me", "status": status});
		
			},
			error: function(xhr, status, error) {
        	// Display a generic error for now.
        		alert("AJAX Error!");
      		}
			
		});
		
	};
	this.auth_params = function(){
		return "&auth_key=" + this.my_user.auth_key + "&chat_auth_key=" + this.to_user.chat_auth_key;
	}
	//this.init();
}

TChat.example = function(from, to){
	if(!TChat.users)
		TChat.users = {};
	if(!TChat.users[1])
		TChat.users[1] = {"id": 1, "username": "joe", "auth_key": "001", "chat_auth_key": "0001"};
	if(!TChat.users[2])
		TChat.users[2] = {"id": 2, "username": "jane", "auth_key": "002", "chat_auth_key": "0002"};
	
	tChat = new TChat(TChat.users[from], TChat.users[to]);
	tChat.register();
	tChat.open();
	return tChat;
}



